
var main = {};
var dex更新信息

// var    downloadDialog = null;
// var    downloadId = -1;
main.main = function (key) {

  // log("检测dex文件更新");
  dex更新信息 = 获取dex更新信息(key);
  filePath = files.join(files.getSdcardPath(),dex更新信息.fileName);
  let localFileVersion = Data.get("Version"+dex更新信息.fileName,"0.0.1");
  log(dex更新信息.version);
  log("当前dex版本: "+localFileVersion)
  let needUpdate = isNeedToUpdateFile(localFileVersion);

  // log(dex更新信息.updateUrl);
 
    if (!files.exists(filePath)|| needUpdate ) {
      files.remove(filePath);
        var downloadDialog = null;
        var downloadId = -1;
        dialogs.build({
          title: "发现新版本",
          content: dex更新信息.version.toString(),
      
          negative: "立即下载",
          neutral: "取消"
      })
          .on("negative", download)
         
          .show();
    
        // 卸载所有jar dex
        
      }else{
    
        // return {
        //   filePath:filePath,
        //   fileName:dex更新信息.fileName
        // }
        runtime.loadDex(filePath);
        try {
          new Packages["主程序"]()();
        } catch (error) {
          toastLog("加载异常 请重新运行")
          files.remove(filePath);
          Data.put("Version"+dex更新信息.fileName,"0.0.1");
        }
        
    
      }
};





// =========自定义函数================

function 获取dex更新信息(key){
  while(true){
    // log("111")
    try {
      key=获取密匙(key)
      //let dexVersionurl ="https://note.youdao.com/yws/api/personal/share?method=get&shareKey=be44d89ed68fdf2ef7c24786f0aa9f60"; //测试地址
      let dexVersionurl ="https://note.youdao.com/yws/api/personal/share?method=get&shareKey="+key; //八八更新地址
    
      let r = http.get(dexVersionurl);
      if (r) {
      r = r.body.json();
      // log(r["entry"]["summary"]); 
      let content = r["entry"]["summary"];

      version = 取文本中间(content,"version:","updateUrl:")
      updateUrl = 取文本右边(content,"updateUrl:")
      fileName = 取文本右边(updateUrl,"/上榜人气/")
      return {
          version: version,
          updateUrl: updateUrl,
          fileName:fileName,
      };
          
      }
    } catch (error) {
    //  log(error)
    }
    sleep(3000)
  }
    
}
function 获取密匙(key){//送礼 纯挂榜 浏览视频 评论业务 开发1 开发2
  switch(key) {
      case "set1":return "b0636bd117604e8fed90b89d1c8303f1";
      case "set2":return "e73962d1fc276e9ef4a1d2a2949c837c";
      case "set3":return "0b1641f7798feaa551b2f450b313febd";
      case "set4":return "8dedbb35bd48700942737bd8f59f0a04";
      case "set5":return "5dfe26141ea57d00b0e901089e1ee43b";
      case "set6":return "0670b3420b0e021663fd89783f70f076";
  } 
  return "";

}
function 取文本右边(str, a) {
  //取文本的中间值
  var w1 = str.indexOf(a);
  if (w1 < 0) {
    return false;
  }
  w1 = w1 + a.length;
  w2 = str.length;
  return str.substr(w1, w2 - w1);
}
function 取文本中间(str, a, b) {
  //取文本的中间值
  var w1 = str.indexOf(a);
  if (w1 < 0) {
    return false;
  }
  w1 = w1 + a.length;
  w2 = str.indexOf(b, w1);
  if (w2 <= 0) {
    return false;
  }
  return str.substr(w1, w2 - w1);
}
function 下载新版dex() {
  let url = dex更新信息.updateUrl;
  //log(url)
  for(let i=0;i<5;i++){
    let r = http.get(url);
    log(r.statusCode)
    if(r.statusCode == 200) {
      files.writeBytes(filePath, r.body.bytes());
      Data.put("Version"+dex更新信息.fileName,dex更新信息.version);
      toastLog("下载完成")
      return filePath;
    }else{
      toast(r.statusCode + "重新连接服务器中")
      sleep(5000)
    }
  }
  toastLog("连接服务器失败!")
  sleep(5000)
  exit()
  
  
}
function isNeedToUpdateFile(localDexVersion) {
  let remoteFileVersion = dex更新信息.version;
  if (remoteFileVersion > localDexVersion) {
    log("需要更新");
    return true;
  } else {
    log("不需要更新");
    return false;
  }
}


function download(){
    threads.start(function () {
    
        runtime.unloadAll(true);
        下载新版dex();
        //log(filePath)
      })
    
    downloadDialog = dialogs.build({
        title: "下载中...",
        positive: "暂停",
        negative: "取消",
        progress: {
            max: 100,
            showMinMax: true
        },
        autoDismiss: false
    })
        .on("positive", ()=>{
            if(downloadDialog.getActionButton("positive") == "暂停"){
                stopDownload();
                downloadDialog.setActionButton("positive", "继续");
            }else{
                startDownload();
                downloadDialog.setActionButton("positive", "暂停");
            }
        })
        .on("negative", ()=>{
            stopDownload();
            downloadDialog.dismiss();
            downloadDialog = null;
        })
        .show();
    startDownload();
}

function startDownload(){
  downloadId = setInterval(()=>{                  //定时器 循环检测文件大小判断下载完成
      var p = downloadDialog.getProgress();
      if(p == 99){
        if(files.exists(filePath)){
          downloadDialog.setProgress(p + 1);
        }
      }else if(p >= 100){
          stopDownload();
          downloadDialog.dismiss();
          downloadDialog = null;
          toast("稍后重启脚本");
          // 获取当前时间后10分钟的时间戳
          let path = engines.myEngine().source.toString();
          let  millis = new Date().getTime() +  5 * 1000;
          // 预定一个10分钟后的任务，这样10分钟后会再次执行本脚本，并再次预定定时任务，从而每10分钟循环
          timers.addDisposableTask({
              path: path,
              date: millis
          });
          exit();
         
      }else{
        
          if(files.exists(filePath)){
            p = 100
            downloadDialog.setProgress(100);
          }else{
            downloadDialog.setProgress(p + 1);
          }
          
      }
  }, 100);
}

function stopDownload(){
    clearInterval(downloadId);
}

// function getRemoteFileVersion() {
//   var data = dex更新信息.version;
//   return data;
// }


module.exports = main;